#pragma once

#include<iostream>
#include<pthread.h>

namespace Lock_Module
{
    class Mutex
    {
        private:
        pthread_mutex_t _mutex;
        public:
        Mutex(const Mutex&)=delete;
        Mutex& operator=(const Mutex&)=delete;
        Mutex()
        {
            int n = ::pthread_mutex_init(&_mutex, nullptr);
            if(n!= 0)
            {
                std::cout << "Mutex init failed" << std::endl;
            }
        }
        ~Mutex()
        {
            int n = ::pthread_mutex_destroy(&_mutex);
            if(n!= 0)
            {
                std::cout << "Mutex destroy failed" << std::endl;
            }
        }
        void lock()
        {
            int n = ::pthread_mutex_lock(&_mutex);
            if(n!= 0)
            {
                std::cout << "Mutex lock failed" << std::endl;
            }
        }
        
        void unlock()
        {
            int n = ::pthread_mutex_unlock(&_mutex);
            if(n!= 0)
            {
                std::cout << "Mutex unlock failed" << std::endl;
            }
        }

        pthread_mutex_t* getMutex()
        {
            return &_mutex;
        }

    };

    class LockGuard
    {
        private:
        Mutex& _mutex;
        public:
        LockGuard(Mutex& mutex):_mutex(mutex)
        {
            _mutex.lock();
        }
        ~LockGuard()
        {
            _mutex.unlock();
        }
    };
}